package com.spring.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.spring.library.common.Result;
import com.spring.library.entity.Book;
import com.spring.library.entity.Record;
import com.spring.library.entity.User;
import com.spring.library.service.IBookService;
import com.spring.library.service.IRecordService;
import com.spring.library.utils.ThreadLocalUtil;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author danty
 * @since 2024-09-19
 */
@RestController
@CrossOrigin
@RequestMapping("/library/record")
public class RecordController {
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IBookService bookService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取借阅记录
     * @return
     */
    @GetMapping("/getRecordList")
    public List<Record> getAll(){
        List<Record> list = recordService.list();
        return list;
    }
    //历史借阅记录
    @GetMapping("/pastBorrowedRecords")
    public Result pastBorrowedRecords(){
        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);

        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getRecordBorrower,user.getUserName());
        List<Record> recordList = recordService.list(recordWrapper);
        System.out.println("recordList = " + recordList);

        System.out.println("曾经的借阅记录");
        return Result.success(recordList);
    }

    /**
     * 根据id删除用户借阅
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        if(!recordService.removeById(id)){
            return Result.error("用户id为空，无法删除");
        }return Result.success("删除成功");
    }
}
